#include <ximera/audio/openal/sounddata.hpp>
#include <ximera/common/utils.hpp>

namespace ximera { namespace audio { namespace openal
{
    SoundData::SoundData()
    {
        alGenBuffers(1, &_buffer);
        openal::checkErrorAndThrow(L"Error generating buffer");
    }

    SoundData::SoundData(String const& fileName)
    {
        alGenBuffers(1, &_buffer);
        openal::checkErrorAndThrow(L"Error generating buffer");

        try
        {
            _buffer = alutCreateBufferFromFile(string_util::wstr2str(fileName).c_str());
            openal::checkErrorAndThrow(L"Error loading wav: " + fileName);

            if (_buffer == AL_NONE)
                XIMERA_THROW(OpenAlException, L"alutCreateBufferFromFile failed");
        }
        catch (...)
        {
            clear();
            throw;
        }
    }

    SoundData::~SoundData()
    {
        clear();
    }

    DataMode SoundData::dataMode() const
    {
        return DataMode::Auto;
    }

    void SoundData::dataMode(DataMode mode)
    {
    }

    ChannelMode SoundData::channelMode() const
    {
        return ChannelMode::Auto;
    }

    void SoundData::channelMode(ChannelMode mode)
    {
    }

    ALuint SoundData::buffer() const
    {
        return _buffer;
    }

    void SoundData::clear()
    {
        alDeleteBuffers(1, &_buffer);
        _buffer = 0;
    }
}}}